package com.team9.fitness.controller;

import com.team9.fitness.entity.UserAvatar;
import com.team9.fitness.service.ZRDDSSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;

/**
 * 用户头像管理控制器
 */
@RestController
@RequestMapping("/api/avatar")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
@Slf4j
public class UserAvatarController {

    @Autowired
    private ZRDDSSendService zrddsSendService;

    /**
     * 上传头像
     */
    @PostMapping("/upload")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> uploadAvatar(@RequestBody Map<String, Object> requestBody) {
        
        try {
            log.info("收到头像上传请求，请求体: {}", requestBody);
            
            Long userId = requestBody.get("userId") != null ? Long.valueOf(requestBody.get("userId").toString()) : null;
            String fileName = (String) requestBody.get("fileName");
            String contentType = (String) requestBody.get("contentType");
            Long fileSize = requestBody.get("fileSize") != null ? Long.valueOf(requestBody.get("fileSize").toString()) : null;
            String base64Data = (String) requestBody.get("base64Data");
            
            log.info("解析参数 - userId: {}, fileName: {}, contentType: {}, fileSize: {}, base64Data长度: {}", 
                    userId, fileName, contentType, fileSize, base64Data != null ? base64Data.length() : 0);
            
            if (userId == null) {
                log.error("用户ID为空");
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return CompletableFuture.completedFuture(ResponseEntity.badRequest().body(result));
            }
            
            if (fileName == null || fileName.isEmpty()) {
                log.error("文件名为空");
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "文件名不能为空");
                return CompletableFuture.completedFuture(ResponseEntity.badRequest().body(result));
            }
            
            if (base64Data == null || base64Data.isEmpty()) {
                log.error("文件数据为空");
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "文件数据不能为空");
                return CompletableFuture.completedFuture(ResponseEntity.badRequest().body(result));
            }
            
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("fileName", fileName);
            requestData.put("fileSize", fileSize);
            requestData.put("contentType", contentType);
            requestData.put("base64Data", base64Data);
            requestData.put("userId", userId);
            
            log.info("发送ZRDDS请求 - requestType: AVATAR_UPLOAD, userId: {}", userId);
            
            return zrddsSendService.sendBusinessRequest("AVATAR_UPLOAD", "POST", "/api/avatar/upload", 
                    userId.toString(), requestData)
                    .thenApply(response -> {
                        log.info("收到ZRDDS响应 - success: {}, message: {}", response.getSuccess(), response.getMessage());
                        Map<String, Object> result = new HashMap<>();
                        if (response.getSuccess()) {
                            result.put("success", true);
                            result.put("message", "头像上传成功");
                            result.put("data", response.getData());
                            log.info("头像上传成功: userId={}", userId);
                        } else {
                            result.put("success", false);
                            result.put("message", response.getMessage() != null ? response.getMessage() : "头像上传失败");
                            log.warn("头像上传失败: userId={}, error={}", userId, response.getError());
                        }
                        return ResponseEntity.ok(result);
                    })
                    .exceptionally(throwable -> {
                        log.error("头像上传异常: userId={}", userId, throwable);
                        Map<String, Object> result = new HashMap<>();
                        result.put("success", false);
                        result.put("message", "头像上传服务异常，请稍后重试");
                        return ResponseEntity.ok(result);
                    });
        } catch (Exception e) {
            log.error("处理头像上传请求异常", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "请求处理失败: " + e.getMessage());
            return CompletableFuture.completedFuture(ResponseEntity.badRequest().body(result));
        }
    }

    /**
     * 获取用户头像
     */
    @GetMapping("/{userId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getUserAvatar(@PathVariable Long userId) {
        
        log.info("获取用户头像请求: userId={}", userId);
        
        return zrddsSendService.sendBusinessRequest("AVATAR_GET", "GET", "/api/avatar/" + userId, 
                userId.toString(), new HashMap<>())
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取头像成功");
                        result.put("data", response.getData());
                        log.info("获取头像成功: userId={}", userId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取头像失败");
                        log.warn("获取头像失败: userId={}, error={}", userId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取头像异常: userId={}", userId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取头像服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 删除用户头像
     */
    @DeleteMapping("/{userId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> deleteUserAvatar(@PathVariable Long userId) {
        
        log.info("删除用户头像请求: userId={}", userId);
        
        return zrddsSendService.sendBusinessRequest("AVATAR_DELETE", "DELETE", "/api/avatar/" + userId, 
                userId.toString(), new HashMap<>())
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "头像删除成功");
                        result.put("data", response.getData());
                        log.info("头像删除成功: userId={}", userId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "头像删除失败");
                        log.warn("头像删除失败: userId={}, error={}", userId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("头像删除异常: userId={}", userId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "头像删除服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }
}
